//*************************************************************************************************************
$(document).ready(function() {
  filterFriend($("#header"), $("#list"));
    appid = $('#appId').val();
    channelUrl = $('#channelUrl').val();
    
    $('.imageRef').each(function(){
    	$(this).attr("src",  $('#imageUrl').val());
    });

    
    window.fbAsyncInit = function () {
        FB.init({
            appId: appid, // App ID
            channelUrl: channelUrl, // Channel File
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true, // parse XFBML
            frictionlessRequests : true
        });
    };
    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));
   
    $(function () {
        $('#activator').click(function () {
            $('#overlay').fadeIn('fast', function () {
                $('#box'+ $('#stepvalue').val()).animate({ 'top': '160px' }, 500);
            });
        });
       
        $('a[id*="boxclose"]').click(function () {
            $('div[id*=box]').animate({ 'top': '-500px' }, 500, function () {
                $('#overlay').fadeOut('fast');
            });
        });

        $('li[id*=next]').click(function () {
            $('#box' + document.getElementById("stepvalue").value).animate({ 'top': '-500px' }, 500);
            $('#stepvalue').val(parseInt($('#stepvalue').val()) + 1);
            $('#overlay').fadeIn('fast', function () {
                $('#box' + ($('#stepvalue').val())).animate({ 'top': '160px' }, 500);
            });
        });

        $('li[id*=pre]').click(function () {
            $('#box' + document.getElementById("stepvalue").value).animate({ 'top': '-500px' }, 500);
            $('#stepvalue').val(parseInt($('#stepvalue').val()) - 1);
            $('#overlay').fadeIn('fast', function () {
                $('#box' + ($('#stepvalue').val())).animate({ 'top': '160px' }, 500);
            });
        });
    });

});

//*************************************************************************************************************
function goNext() {
    $('#box' + document.getElementById("stepvalue").value).animate({ 'top': '-500px' }, 500);
    $('#stepvalue').val(parseInt($('#stepvalue').val()) + 1);
    $('#overlay').fadeIn('fast', function () {
        $('#box' + ($('#stepvalue').val())).animate({ 'top': '160px' }, 500);
    });
}
//*************************************************************************************************************

    function loggedin() {
        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                FB.api('/me', function (user) {
                    if (!($("#fbid").val()) && ($("#UserName").val())) {
                        alert('Authentication Failed!');
                    }
                    else {
                        $("#fbid").val(user.id);
                        $("#firstName").val(user.first_name);
                        $("#lastName").val(user.last_name);
                        $("#userName").val(user.email);
                        $("#emailAddress").val(user.email);
                        getFriends();
                    }
                });
            }
        });
    }
    
//*************************************************************************************************************
    //function to load friends
    function loadFriends() {
        //get array of friends
        FB.api('/me/friends', function (response) {
            //console.log(response);
            var divContainer = $('#facebookFriendList');
            for (i = 0; i < response.data.length; i++) {
                $(document.createElement("div")).attr({ id: 'facebookFriendListItem' + i, class: 'facebookimages' }).appendTo(divContainer);
                $(document.createElement("img")).attr({ src: 'https://graph.facebook.com/' + response.data[i].id + '/picture', title: response.data[i].name, onClick: 'selectFriend(' + response.data[i].id + ',"' + response.data[i].name + '");' }).appendTo(document.getElementById('facebookFriendListItem' + i));
            }
        });
    }

    function getFriends(){
      var theword = '/me/friends';
      FB.api(theword, function(response) {
        var divInfo = document.getElementById("facebookFriendList");
        var divList = ""
        var friends = response.data;
        for (var i = 0; i < friends.length; i++) {
          divList += '<li class="friendlist" Style="background-image:url(https://graph.facebook.com/'+ friends[i].id +'/picture)">'
          divList += '<a onclick="selectFriend('+ friends[i].id +',\'' + friends[i].name +'\');" href="#/'+friends[i].id +'">' + friends[i].name + '</a></li>';
         }
        divInfo.innerHTML += '<ul id="list">' + divList + '</ul></div>';  
       });
      }
    
    function filterFriend(header, list){
       
      input = $("#txtSearchFriends");
      $("#txtSearchFriends")
        .change( function () {
          var filter = $(this).val();
          
          if(filter) {
            $("#list").find("a:not(:Contains(" + filter + "))").parent().slideUp();
            $("#list").find("a:Contains(" + filter + ")").parent().slideDown();
          } else {
            $("#list").find("li").slideDown();
          }
          return false;
        })
      .keyup( function () {
          // fire the above change event after every letter
          $(this).change();
      });
      
    }

//*************************************************************************************************************

    function selectFriend(id,name) {
        var divContainer = $('#selectedFriends');
        divContainer.append('<div class="uiToken ' + id + '">' + name +  '&nbsp<span onclick="$(\'.' + id + '\').remove();" class="uiToken">x</span>' + '</div>');
        
        var tempdata = {};
        tempdata['id'] = id;
        tempdata['name'] = name;
        $.cookie("tempdata", JSON.stringify(tempdata);
        consol.log()
        //@[100002829810133]  data: JSON.stringify(tempdata),    dataType: 'json',
                 
    }

//*************************************************************************************************************
    function sendSelectedFreind() {
        var divContainer = $('#selectedFriends');
        var divfinalSelectedFriends = $('#finalSelectedFriends');
        divfinalSelectedFriends.append(divContainer.html());
    }
    
//*************************************************************************************************************

    function sendMultipleMessage(text) {
      var  arr = [];

      arr.push('1297092863');
      arr.push('100002126219072');
        FB.getLoginStatus(function (response) {
            FB.ui(
                 {
                     method: 'send',
                     to: arr ,
                     picture: $('#imageUrl').val(),
                     link: $('#messageLink').val(),
                     description:'avc' ,//$('#conversationText').val(),
                     caption:'edc',
                     name:'gft',
                     display: 'iframe'
                 },
                 function (param) {
                     if (!param.success){
                         $('li[id*=pre]').click();
                     }
                     else{
                            $('div[id*=box]').animate({ 'top': '-500px' }, 500, function () {
                            $('#overlay').fadeOut('fast');
                            });
                     }
                });
             });
      }
    
//*************************************************************************************************************
//TODO:SA:Please correct the IDs in below
    function sendApprequests(text) {
      var  arr = [];
      
      arr.push('100002126219072');
      arr.push('1297092863');
      
           FB.getLoginStatus(function (response) {
            FB.ui(
            {
              app_id:   $('#appId').val(),
                method: 'apprequests',
                message: "my app request message",
                picture: $('#imageUrl').val(),
                title: 'Shahab jan',
                to:arr,
            }, function(response) {
                if(response && response.hasOwnProperty('to')) {
                    for(i = 0; i < response.to.length; i++) {
                        console.log("" + i + " ID: " + response.to[i]);
                    }
                }
                else  {
                  alert(response);
                }
            });
        });
    }
    
//*************************************************************************************************************
    
    function sendfeed(text) {
      FB.getLoginStatus(function (response) {
        FB.ui(
            {
              method: 'feed',
              name: 'Facebook Dialogs',
              link: $('#messageLink').val(),
              picture: $('#imageUrl').val(),
              caption: 'Reference Documentation',
              description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
            },
            function(response) {
              if (response && response.post_id) {
                alert('Post was published.');
              } else {
                alert('Post was not published.');
              }
            }
          );
      });
    }

//*************************************************************************************************************    
    
    function sendMessageRead(){
      //document.domain= 'facebook.com';
      //alert($(".FB_UI_Dialog").contents().find("feedform_user_message").val());
      
    }

//*************************************************************************************************************
    
    function SendEmail() {
        //Call webservice to send e-mail e.g.
        
        $.ajax({ type: 'POST',
            url: 'https://www.facebook.com/dialog/sendapp_id=370960029693800&to=1297092863&link=http://www.cymax.com/South-Shore-3070-23X-Lexington-Platform-Bed.htm&redirect_uri=http://localhost:8888/base.html',
            success: function (response) {
                console.log(response);
            },
            error: function(error) {
                alert(error.status);
            }
        });
    }
    
//*************************************************************************************************************
    
    function sendNotification() {
      var param = 'https://apps.facebook.com/'+ $('#appId').val()+'/fb_source=myapps' ;
      var tempdata = {};
      tempdata['access_token'] = $('#app_secret').val();
      tempdata['href'] = param;
      tempdata['template'] = 'started a game with you!';
      //@[100002829810133]  data: JSON.stringify(tempdata),    dataType: 'json',
               
      console.log(JSON.stringify(tempdata));
      
      FB.getLoginStatus(function (response) {
        $.ajax({ type: 'POST',
            url:'https://graph.facebook.com/'+ $("#fbid").val() +'/notificationsaccess_token=' + $('#app_secret').val() + '&href=' + param + '&template= started a game with you!' ,
            success: function (response) {
                console.log(response);
            },
            error: function(error) {
                  alert(error.status);
            }
        });
      });
    }
        
//*************************************************************************************************************
        
    function getContent(){
      var response = '';
      $.ajax({
        type: "GET",  
        url: $('#messageLink').val(),
        async: false,
            success : function(text)
            {
                response = text;
            }
         });
          alert(response);
     }
        
//*************************************************************************************************************        
        
    function getImage(){
      $.ajax({
        url:  $('#messageLink').val(),
        beforeSend: function ( xhr ) {
        xhr.overrideMimeType("text/plain; charset=x-user-defined");
        }
        }).done(function ( data ) {
        if( console && console.log ) {
        console.log("Sample of data:", data.slice(0, 100));
        }
        });
    }
    
    
  //*************************************************************************************************************
